<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="考核名称" prop="examName">
        <el-input
          v-model="queryParams.examName"
          placeholder="请输入考核名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="考核状态" prop="examStatus">
        <el-select
          v-model="queryParams.examStatus"
          placeholder="考核状态"
          clearable
        >
          <el-option
            v-for="item in examStatusList"
            :key="item.status"
            :label="item.label"
            :value="item.status"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="开始时间">
        <el-date-picker
          v-model="startDateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间">
        <el-date-picker
          v-model="endDateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>


    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['exam:add']"
        >新增</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>


    <el-table
      ref="tables"
      v-loading="loading"
      :data="examList"
    >
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="考试名称" align="center" prop="examName" />
      <el-table-column label="考试状态" align="center" prop="status" >
        <template slot-scope="scope">
              <span>{{
                  statusVal(scope.row.status)
                }}</span>
        </template>
      </el-table-column>
      <el-table-column label="试卷" align="center" prop="examTheory.paperId" >
        <template slot-scope="scope">
              <span>{{
                  paperVal(scope.row.examTheory.paperId)
                }}</span>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="startTime" >
        <template slot-scope="scope">
              <span>{{
                  parseTime(scope.row.startTime, "{y}-{m}-{d} {h}:{i}:{s}")
                }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" >
        <template slot-scope="scope">
              <span>{{
                  parseTime(scope.row.endTime, "{y}-{m}-{d} {h}:{i}:{s}")
                }}</span>
        </template>
      </el-table-column>
      <el-table-column label="理论考核时长(分钟)" align="center" prop="examTheory.examTime" />
      <el-table-column
        label="操作"
        align="center"
        width="160"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-row>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['exam:update']"
              >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-document"
              @click="handleScoreList(scope.row)"
              v-hasPermi="['exam:update']"
            >成绩列表</el-button>
            <router-link :to="'/paperView/index/' + scope.row.examTheory.paperId" class="link-type">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-view"
                style="padding:5px"
                v-hasPermi="['exam:paper:list']"
              >预览试卷</el-button>
            </router-link>
          </el-row>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNo"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增 -->
    <el-dialog
      :title="addTitle"
      :visible.sync="addExamView"
      width="600px"
      append-to-body
    >
      <el-form ref="form" :model="addExamForm" :rules="addExamFormRules" label-width="140px">
        <el-form-item label="考试名称" prop="examName">
          <el-input v-model="addExamForm.examName" placeholder="请输入考试名称" />
        </el-form-item>
        <el-form-item label="考试状态" prop="examStatus">
          <el-select
            v-model="addExamForm.status"
            placeholder="考核状态"
            clearable
          >
            <el-option
              v-for="item in examStatus"
              :key="item.status"
              :label="item.label"
              :value="item.status"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="试卷" prop="paperId">
          <el-select
            v-model="addExamForm.examTheory.paperId"
            placeholder="试卷"
            clearable
          >
            <el-option
              v-for="item in paper.list"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="考试时间">
          <el-date-picker
            v-model="addExamFormTime"
            style="width: 240px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="onAddExamFormTimeChange"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="理论考核时长(分钟)" prop="examTime">
          <el-input-number v-model="addExamForm.examTheory.examTime" placeholder="请输入理论考核时长（分钟）" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAddExamForm">确 定</el-button>
        <el-button @click="addExamView = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 更新 -->
    <el-dialog
      :title="updateTitle"
      :visible.sync="updateExamView"
      width="600px"
      append-to-body
    >
      <el-form ref="form" :model="updateExamForm" :rules="addExamFormRules" label-width="140px">
        <el-form-item label="考试名称" prop="examName">
          <el-input v-model="updateExamForm.examName" placeholder="请输入考试名称" />
        </el-form-item>
        <el-form-item label="考试状态" prop="examStatus">
          <el-select
            v-model="updateExamForm.status"
            placeholder="考核状态"
            clearable
          >
            <el-option
              v-for="item in examStatus"
              :key="item.status"
              :label="item.label"
              :value="item.status"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="试卷" prop="paperId">
          <el-select
            v-model="updateExamForm.examTheory.paperId"
            placeholder="试卷"
            clearable
          >
            <el-option
              v-for="item in paper.list"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="考试时间">
          <el-date-picker
            v-model="updateExamFormTime"
            style="width: 240px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="onUpdateExamFormTimeChange"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="理论考核时长(分钟)" prop="examTime">
          <el-input-number v-model="updateExamForm.examTheory.examTime" placeholder="请输入理论考核时长（分钟）" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitUpdateExamForm">确 定</el-button>
        <el-button @click="updateExamView = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 成绩列表 -->
    <el-dialog
      title="成绩列表"
      :visible.sync="scoreView"
      width="1400px"
      append-to-body
      @close="scoreViewClose"
    >
      <el-form
        :model="scoreParams"
        ref="queryForm"
        size="small"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
      >
        <el-form-item label="学员ID" prop="uid">
          <el-input
            v-model="scoreParams.uid"
            placeholder="请输入考核名称"
            clearable
            @keyup.enter.native="handleScoreQuery"
          />
        </el-form-item>
        <el-form-item label="学员昵称" prop="userNickname">
          <el-input
            v-model="scoreParams.userNickname"
            placeholder="请输入学员昵称"
            clearable
            @keyup.enter.native="handleScoreQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleScoreQuery"
          >搜索</el-button
          >
        </el-form-item>
      </el-form>
      <el-table
        ref="tables"
        v-loading="scoreLoading"
        :data="scoreList"
      >
        <el-table-column label="学员ID" align="center" prop="scores.uid" />
        <el-table-column label="学员昵称" align="center" prop="nickname" />
        <el-table-column label="综合成绩" align="center" prop="scores.scores" />
        <el-table-column label="综合排行" align="center" prop="scores.scoresRanking" />
        <el-table-column label="综合时间" align="center" prop="scores.multipleTime" />
        <el-table-column label="综合时间排行" align="center" prop="scores.multipleTimeRanking" />
        <el-table-column label="实操" align="center" prop="scores.handsOnScore" />
        <el-table-column label="实操排行" align="center" prop="scores.handsOnScoreRanking" />
        <el-table-column label="实操耗时" align="center" prop="scores.handsOnTime" />
        <el-table-column label="实操耗时排行" align="center" prop="scores.handsOnTimeRanking" />
        <el-table-column label="理论" align="center" prop="scores.theoryScore" />
        <el-table-column label="理论排行" align="center" prop="scores.theoryScoreRanking" />
        <el-table-column label="理论耗时" align="center" prop="scores.theoryTime" />
        <el-table-column label="理论耗时排行" align="center" prop="scores.theoryTimeRanking" />
      </el-table>
    </el-dialog>

  </div>
</template>

<script>
import { listExam,addExam,updateExam ,subjectCategory ,listScore} from "@/api/exam/exam";
import { isArray } from 'util'
import { all } from '@/api/exam/paper'

export default {
  name: "Exam",
  data() {
    return {
      queryParams: {
        examName: null,
        examStatus: null,

        pageNo: 1,
        pageSize: 10,
      },
      startDateRange: [],
      endDateRange: [],

      scoreList: [],
      scoreView: false,
      scoreTotal: 0,
      scoreLoading: false,
      currExamId: -1,
      scoreParams: {
        examId: -1,
        uid: null,
        userNickname: null,

        pageNo: 1,
        pageSize: 10,
      },

      examStatus: [
        {status: 0 , label: '未开始'},
        {status: 1 , label: '进行中'},
        {status: 2 , label: '已结束'},
        {status: -1 , label: '未启用'}
      ],

      categoryList: [], //科目分类
      addExamSubjectCategorySelect: null,
      currentExamSubject: null,

      showSearch: true,
      examStatusList: [],

      loading: true,
      examList: null,
      total: 0,

      addExamView: false,
      addTitle: '新增考试',
      addExamForm: {
        examName: null,
        status: null,
        startTime: null,
        endTime: null,
        examTheory:{
          paperId: null,
          examTime: null,
        }
      },
      addExamFormTime: [],
      addExamFormRules: {
        examName: [{ required: true, message: "考试名称不能为空", trigger: "blur" }],
        startTime: [{ required: true, message: "考试时间不能为空", trigger: "blur" }],
      },

      updateExamView: false,
      updateTitle: '更新考试信息',
      updateExamForm: {
        id: null,
        examName: null,
        status: null,
        startTime: null,
        endTime: null,
        examTheory:{
          paperId: null,
          examTime: null
        }
      },
      updateExamFormTime: [],

      paper: {
        open: false,
        list: [],
        data: {
        },
      }
    };
  },
  created() {
    this.examStatusList = Array.from(this.examStatus);
    this.examStatusList.unshift({status: null , label: '全部'});
    this.getPaperList();
    this.getList();
  },
  methods: {
    /** 查询任务列表 */
    getList() {
      this.loading = true;
      if(this.startDateRange.length  > 0){
        // this.addDateRange(this.queryParams, this.startDateRange ,'StartTime');
        this.queryParams.beginStartTime = new Date(this.startDateRange[0]).getTime() / 1000;
        this.queryParams.endStartTime = new Date(this.startDateRange[1]).getTime() / 1000;
      }
      if(this.endDateRange.length > 0){
        // this.addDateRange(this.queryParams, this.endDateRange ,'EndTime');
        this.queryParams.beginEndTime = this.startDateRange[0];
        this.queryParams.endEndTime = this.endDateRange[1];
      }
      let param = {...this.queryParams};
      param.pageNo --;
      listExam(param).then(
        (response) => {
          this.examList = response.rows;
          this.total = parseInt(response.total);
          this.loading = false;
        }
      );
    },
    async getPaperList(){
      await all().then(resp => {
        this.paper.list = resp.data;
      });
    },
    getScoreList(){
      this.scoreView = true;
      this.scoreLoading = true;
      let param = {...this.scoreParams};
      param.examId = this.currExamId;
      param.pageNo --;
      listScore(param).then(resp => {
        this.scoreList = resp.rows;
        this.scoreTotal = parseInt(resp.total);
        this.scoreLoading = false;
      });
    },
    statusVal(status){
      for (let s of this.examStatus){
        if(s.status == status){
          return s.label;
        }
      }
    },
    paperVal(paperId){
      for(let paper of this.paper.list){
        if(paper.id == paperId){
          return paper.name;
        }
      }
    },
    scoreViewClose(){
      this.scoreView = false;
      this.currExamId = null;
    },
    handleScoreQuery(){
      this.scoreParams.pageNo = 1;
      this.getScoreList();
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.startDateRange = [];
      this.endDateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },


    /** 详细按钮操作 */
    handleView(row) {
      this.taskNo = row.taskNo;
      this.taskView = true;
      const taskId = row.taskId;
      getTask(taskId).then((response) => {
        this.evaluate = response.data;
        this.title = "考核详情";
      });

      //人员信息
      this.getPersonlTaskList();
    },

    handleAdd(){
      this.addExamView = true;
    },

    /** 成绩列表*/
    handleScoreList(row){
      this.currExamId = row.id;
      this.getScoreList();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.updateExamView = true;
      this.updateExamForm = {
        id: row.id,
        examName: row.examName,
        status: row.status,
        startTime: row.startTime,
        endTime: row.endTime,
        examTheory: {
          id: row.examTheory.id,
          examTime: row.examTheory.examTime
        }
      }
      this.updateExamFormTime = [
        this.parseTime(row.startTime, "{y}-{m}-{d} {h}:{i}:{s}"),
        this.parseTime(row.endTime, "{y}-{m}-{d} {h}:{i}:{s}")
      ];
    },
    onAddExamFormTimeChange(val){
      console.log(val);
      this.addExamForm.startTime = Date.parse(new Date(val[0])) / 1000;
      this.addExamForm.endTime = Date.parse(new Date(val[1])) / 1000;
    },
    onUpdateExamFormTimeChange(val){
      this.updateExamForm.startTime = Date.parse(new Date(val[0])) / 1000;
      this.updateExamForm.endTime = Date.parse(new Date(val[1])) / 1000;
    },
    /** 提交新增*/
    submitAddExamForm(){
      if(!this.checkSubmitData(this.addExamForm ,this.addExamFormRules)){
        return;
      }
      addExam(this.addExamForm).then(resp => {
          this.getList();
          this.addExamView = false;

      });
    },
    submitUpdateExamForm(){
      if(!this.checkSubmitData(this.updateExamForm ,this.addExamFormRules)){
        return;
      }
      updateExam(this.updateExamForm).then(resp => {
        this.getList();
        this.updateExamView = false;
      });
    },
    checkSubmitData(data ,rules){
      for(let key in rules){
        if(rules[key][0] && rules[key][0].required){
          if(!data[key] || (isArray(data[key]) && data[key].length == 0)){
            this.$modal.msgError(rules[key][0].message);
            return false;
          }
        }
      }
      return true;
    },
  },
};
</script>
